package com.ykq.springsecurity04.service;

import com.ykq.springsecurity04.dao.PermissionDao;
import com.ykq.springsecurity04.dao.UserDao;
import com.ykq.springsecurity04.entity.Permission;
import com.ykq.springsecurity04.entity.Users;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @program: springsecurity04
 * @description:
 * @author: 闫克起2
 * @create: 2022-11-01 15:18
 **/
@Service //该类对象的生命周期交于spring容器管理
public class MyUserService implements UserDetailsService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private PermissionDao permissionDao;

    //注入 dao对象---根据账户查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        Users users = userDao.selectByUsername(username);
        if(users!=null){
            //该用户具有的权限
            Collection<GrantedAuthority> authorities=new ArrayList<>();
            //根据用户id查询该用户具有的权限。
            List<Permission> permissions = permissionDao.findByUserid(users.getUserid());

            //把上面的权限封装authorities中----jdk1.8 Stream流--
//            authorities=permissions.stream()
//                                   .map(item->new SimpleGrantedAuthority(item.getPercode()))
//                                   .collect(Collectors.toList());

            for(Permission item:permissions){
                SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(item.getPercode());
                authorities.add(simpleGrantedAuthority);
            }

            User user=new User(username,users.getUserpwd(),authorities);
            return user;
        }
        return null;
    }
}













